﻿using FreesenseSubAIS.Core;
using FreesenseSubAIS.ImageProcess;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FreesenseSubAIS.UI
{
    public partial class YieldAnalyForm : Form
    {
        List<string> recordlist;
        List<string> timelist;
        DataTable dtable;
        List<string> sb;
        public YieldAnalyForm()
        {
            InitializeComponent();
        }

        private void Query_Btn_Click(object sender, EventArgs e)
        {
            try
            {
                statusLable.Text = "";
                statusLable.BackColor = Color.Gray;
                if (dtable != null)
                    dtable.Dispose();
                var time1 = radDateTimePicker1.Value;
                var time2 = radDateTimePicker2.Value;
                if (time1 > time2)
                    return;
                timelist = new List<string>();
                for (DateTime dt = time1; dt <= time2; )
                {
                    timelist.Add(dt.ToString("yyyyMMdd"));
                    dt = dt.AddDays(1);
                }
                var time = timelist.Select(x => x).Where(x => recordlist.Any(y => y.Contains(x))).ToList ();
                if (time.Count == 0 || recordlist == null)
                {
                    MessageBox.Show("未找到区间的记录");
                    return;
                }
#if true
                var dataTableArray = new List<DataTable>();
                foreach (var element in time)
                {
                    var path = Path.Combine("Log", Device.defaultProduct.ProductName, recordlist.First(x => x.Contains(element)));
                    dataTableArray.Add((new ExcelHelper(path)).ExcelToDataTable("API", true));
                }
                if (dataTableArray.Count > 0)
                    dtable = dataTableArray[0];
                for (int i = 1; i < dataTableArray.Count; i++)
                {
                    if (dataTableArray[i] != null)
                        foreach (DataRow dr in dataTableArray[i].Rows)
                        {
                            dtable.ImportRow(dr);
                        }
                    //dtable .
                    //var table = from rHead in dataTableArray[i].AsEnumerable()
                    //            join rTail in dtable.AsEnumerable()
                    //            on rHead.Field<string>("BatchID") equals rTail.Field<string>("BatchID")
                    //            select rHead.ItemArray.Concat(rTail.ItemArray);//.Skip(1)
                    //foreach (var obj in table)
                    //{
                    //    DataRow dr = dtable.NewRow();
                    //    var temp=obj.AsEnumerable ().ToList(); 
                    //    dr.ItemArray = obj.ToArray();
                    //    dtable.Rows.Add(dr);
                    //}
                }

#elif true
                var first = recordlist.First(x => x.Contains(time.First()));
                first = Path.Combine("Log", Device.defaultProduct.ProductName, first);
                dtable = (new ExcelHelper(first)).ExcelToDataTable("API", true);
#endif
                dataGridView1.DataSource = dtable;
                RefrushListView((time2 - time1).Days, time.Count());
                statusLable.Text = "操作成功！";
                statusLable.ForeColor = Color.RoyalBlue;
            }
            catch (Exception ex)
            {
                statusLable.ForeColor = Color.Red;
                MessageBox.Show("查询失败！" + ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void YieldAnalyForm_Load(object sender, EventArgs e)
        {
            listView1 .ShowItemToolTips =true;
            radDateTimePicker1.Value = DateTime.Now;
            radDateTimePicker2.Value = DateTime.Now;
            string path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Log", Device.defaultProduct.ProductName);
            if (Directory.Exists(path))
            {
                string[] productList = Directory.GetFiles(path);
                recordlist = new List<string>();
                foreach (string pa in productList)
                {
                    recordlist.Add(Path.GetFileName(pa));
                }
            }
            var source = Device.DeviceEntityControl.Cameras.Select(x => x.CameraName).ToList();
            comboBox1.DataSource = source;
        }
        private void RefrushListView(int days, int invidcount)
        {
            if (dtable == null)
                return;
            listView1.Items.Clear();
            sb = new List<string>();
            sb.Add(string.Format("查询起点：{0}", radDateTimePicker1.Value.ToString()));
            sb.Add(string.Format("查询终点：{0}", radDateTimePicker2.Value.ToString()));
            sb.Add(string.Format("区间天数：{0}，有效记录：{1}", days + 1, invidcount));

            if (dtable.Columns.Contains("ErrCode"))
            {
                var data = dtable.AsEnumerable().Select(x => new
                    {
                        PanelID = x.Field<string>("PanelID"),
                        Result = x.Field<string>("Result"),
                        ErrCode = x.Field<string>("ErrCode"),
                    });
                var oknum = data.AsEnumerable().Count(x => x.Result.Equals("OK"));
                var ngnum = data.AsEnumerable().Count(x => x.Result.Equals("NG"));
                sb.Add(string.Format("总产量:{0}", oknum + ngnum));
                sb.Add(string.Format("OK数量:{0}", oknum));
                sb.Add(string.Format("NG数量:{0}", ngnum));
                sb.Add(string.Format("良率:{0}%", oknum * 100 / (oknum + ngnum)));
                var query = from p in dtable.AsEnumerable()
                            group p by p.Field<string>("ErrCode") into g
                            select new
                            {
                                ErrType = g.Key,
                                ErrCount = g.Count()
                            };
                query.AsEnumerable().ToList().ForEach(x =>
                    {
                        if (x.ErrType != null)
                            sb.Add(string.Format("不良类型：{0}，数量：{1}", x.ErrType, x.ErrCount));
                    });
            }
            foreach (var str in sb)
                listView1.Items.Add(str);
        }

        private void Output_Btn_Click(object sender, EventArgs e)
        {
            try
            {
                statusLable.Text = "";
                statusLable.BackColor = Color.Gray;
                StringBuilder strb = new StringBuilder();
                foreach (var str in sb)
                    strb.Append(str + "##");
                Utiles.SaveDebugLog(strb, comboBox1.Text);
                string msg = string.Format("存放路径为：软件运行目录\\Log\\{0}\\{1}\\{2}", comboBox1.Text, DateTime.Now.ToString("yyyyMMdd"), "良率分析.txt");
                statusLable.Text = msg;
                statusLable.BackColor = Color.RoyalBlue ;
            }
            catch(Exception ex)
            {
                statusLable.Text = "错误：" + ex.Message ;
                statusLable.BackColor = Color.Red ;
            }
        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            StringBuilder strb = new StringBuilder();
            foreach (var str in sb)
                strb.Append(str+"\r\n");
            try
            {
                Clipboard.SetDataObject(strb.ToString ());

                string info = string.Format("已经复制到剪贴板");
                toolTip1.Show(info, this.listView1, 50, 50, 1000);
                //notifyIcon1.ShowBalloonTip(1500, "提示", info, ToolTipIcon.Info);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }
}
